#include "unp.h"

volatile sig_atomic_t mqflag;

static void sig_usr1(int signo);

mqd_t mqd;
void  *buff;
struct mq_attr attr;
struct sigevent sigev;

int main(int argc,char *argv[])
{
   //int rc = -1;
   sigset_t zeromask,newmask,oldmask;
   sigemptyset(&zeromask);
   sigemptyset(&newmask);
   sigemptyset(&oldmask);
   sigaddset(&newmask,SIGUSR1);

   mqd = mq_open(argv[1],O_RDONLY | O_NONBLOCK);
   if(mqd == -1)
     err_sys("mq_open error");
   if(mq_getattr(mqd,&attr) == -1)
     err_sys("mq_getattr error");
 
   buff = malloc(attr.mq_msgsize);

   signal(SIGUSR1,sig_usr1);
   sigev.sigev_notify=SIGEV_SIGNAL;
   sigev.sigev_signo =SIGUSR1;
   if(mq_notify(mqd,&sigev) ==-1)
     err_sys("mq_notify error");


   for(;;){
     sigprocmask(SIG_BLOCK,&newmask,&oldmask);
     while(mqflag==0){
       sigsuspend(&zeromask);
     }
     mqflag = 0;
     ssize_t n;
     u_int32_t prio;
     printf("sig_usr1 begin\n");
     if(mq_notify(mqd,&sigev) ==-1)
        err_sys("mq_notify error");
     while((n=mq_receive(mqd,buff,attr.mq_msgsize,&prio)) !=-1){
        printf("SIGUSR1 received, read %ld bytes\n",(long)n);
     }
     sigprocmask(SIG_UNBLOCK,&newmask,NULL);
   }
   exit(0);
}

static void sig_usr1(int signo){
   printf("SIGUSR1 received %d\n",mqflag); 
   mqflag = 1;
   return;
}
